<?php
/**
 * 支付入口
 *
 *
 **by 好商城V3 www.33hao.com 运营版*/
//use PHPQrcode;
defined('InShopNC') or exit('Access Invalid!');
require_once BASE_ROOT_PATH.'/shop/api/payment/wxpay/example/phpqrcode/phpqrcode.php';//E:\XM\shopnc\shop\api\payment\wxpay\example\phpqrcode
require_once BASE_ROOT_PATH.'/shop/api/payment/wxpay/example/log.php';//E:\XM\shopnc\shop\api\payment\wxpay\example\log.php
require_once BASE_ROOT_PATH.'/shop/api/payment/alipay_new/AlipayGather.php';//E:\XM\shopnc\shop\api\payment\alipay_new
class paymentControl extends BaseHomeControl
{

    public function __construct()
    {
        //向前兼容
        $_GET['extra_common_param'] = str_replace(array('predeposit', 'product_buy'), array('pd_order', 'real_order'), $_GET['extra_common_param']);
        $_POST['extra_common_param'] = str_replace(array('predeposit', 'product_buy'), array('pd_order', 'real_order'), $_POST['extra_common_param']);
    }

    /**
     * 实物商品订单
     */

    public function real_orderOp()
    {
        $pay_sn = $_POST['pay_sn'];
        $payment_code = $_POST['payment_code'];
        $url = 'index.php?act=member_order';

        if (!preg_match('/^\d{18}$/', $pay_sn)) {
            showMessage('参数错误', '', 'html', 'error');
        }
        $logic_payment = Logic('payment');
        $result = $logic_payment->getPaymentInfo($payment_code);
        if (!$result['state']) {
            showMessage($result['msg'], $url, 'html', 'error');
        }

        $payment_info = $result['data'];

        //计算所需支付金额等支付单信息
        $result = $logic_payment->getRealOrderInfo($pay_sn, $_SESSION['member_id']);

        if (!$result['state']) {
            showMessage($result['msg'], $url, 'html', 'error');
        }
        if ($result['data']['api_pay_state'] || empty($result['data']['api_pay_amount'])) {
            showMessage('该订单不需要支付', $url, 'html', 'error');
        }

        //var_dump($result['data']);
        //var_dump($payment_info['payment_code']);die;

        if ($payment_info['payment_code'] == 'predeposit') { //余额支付
            $this->_amount_pay($result['data'], $payment_info, $url);
        } else {
            //转到第三方API支付
            $this->_api_pay($result['data'], $payment_info);
        }
    }

    public function get_wxpay_codeOp(){
        $url = urldecode($_GET["data"]);
        if(substr($url, 0, 6) == "weixin"){
            QRcode::png($url);
        }else{
            header('HTTP/1.1 404 Not Found');
        }

    }

    /**
     * 虚拟商品购买
     */
    public function vr_orderOp()
    {
        $order_sn = $_POST['order_sn'];
        $payment_code = $_POST['payment_code'];
        $url = 'index.php?act=member_vr_order';

        if (!preg_match('/^\d{18}$/', $order_sn)) {
            showMessage('参数错误', '', 'html', 'error');
        }

        $logic_payment = Logic('payment');
        $result = $logic_payment->getPaymentInfo($payment_code);
        if (!$result['state']) {
            showMessage($result['msg'], $url, 'html', 'error');
        }
        $payment_info = $result['data'];

        //计算所需支付金额等支付单信息
        $result = $logic_payment->getVrOrderInfo($order_sn, $_SESSION['member_id']);
        if (!$result['state']) {
            showMessage($result['msg'], $url, 'html', 'error');
        }

        if ($result['data']['order_state'] != ORDER_STATE_NEW || empty($result['data']['api_pay_amount'])) {
            showMessage('该订单不需要支付', $url, 'html', 'error');
        }

        //转到第三方API支付
        $this->_api_pay($result['data'], $payment_info);
    }

    /**
     * 预存款充值
     */
    public function pd_orderOp()
    {
        $pdr_sn = $_POST['pdr_sn'];
        $payment_code = $_POST['payment_code'];
        $url = 'index.php?act=predeposit';

        if (!preg_match('/^\d{18}$/', $pdr_sn)) {
            showMessage('参数错误', $url, 'html', 'error');
        }

        $logic_payment = Logic('payment');
        $result = $logic_payment->getPaymentInfo($payment_code);
        if (!$result['state']) {
            showMessage($result['msg'], $url, 'html', 'error');
        }
        $payment_info = $result['data'];

        $result = $logic_payment->getPdOrderInfo($pdr_sn, $_SESSION['member_id']);
        if (!$result['state']) {
            showMessage($result['msg'], $url, 'html', 'error');
        }
        if ($result['data']['pdr_payment_state'] || empty($result['data']['api_pay_amount'])) {
            showMessage('该充值单不需要支付', $url, 'html', 'error');
        }

        //转到第三方API支付
        $this->_api_pay($result['data'], $payment_info);
    }

    /**
     * 第三方在线支付接口
     *
     */
    private function _api_pay($order_info, $payment_info)
    {
        if ($payment_info['payment_code'] == 'alipay') {
            $this->_alipay($order_info, $payment_info);
            exit();
        }
        if ($payment_info['payment_code'] == 'wxpaystatus') {
            $this->_wxpay($order_info, $payment_info);
            exit();
        }
        $payment_api = new $payment_info['payment_code']($payment_info, $order_info);
        if ($payment_info['payment_code'] == 'chinabank') {
            $payment_api->submit();
        } else {
            @header("Location: " . $payment_api->get_payurl());
        }
        exit();
    }
    public function _wxpay($order_info, $payment_info)
    {
        $alipay_path = BASE_ROOT_PATH . '/shop/api/payment/wxpay/example/';//E:\XM\shopnc\shop\api\payment\wxpay\example
        //require $alipay_path . 'wxpay.php';
        die;
    }


    /**
     * 通知处理(支付宝异步通知和网银在线自动对账)
     *
     */
    public function notifyOp()
    {
        switch ($_GET['payment_code']) {
            case 'alipay':
                $success = 'success';
                $fail = 'fail';
                break;
            case 'wxpay':
                $success = 'success';
                $fail = 'fail';
                break;
            case 'chinabank':
                $success = 'ok';
                $fail = 'error';
                break;
            default:
                exit();
        }

        $order_type = $_POST['extra_common_param'];
        $out_trade_no = $_POST['out_trade_no'];
        $trade_no = $_POST['trade_no'];

        //参数判断
        if (!preg_match('/^\d{18}$/', $out_trade_no)) exit($fail);

        $model_pd = Model('predeposit');
        $logic_payment = Logic('payment');

        if ($order_type == 'real_order') {

            $result = $logic_payment->getRealOrderInfo($out_trade_no);
            if (intval($result['data']['api_pay_state'])) {
                exit($success);
            }
            $order_list = $result['data']['order_list'];

        } elseif ($order_type == 'vr_order') {

            $result = $logic_payment->getVrOrderInfo($out_trade_no);
            if ($result['data']['order_state'] != ORDER_STATE_NEW) {
                exit($success);
            }

        } elseif ($order_type == 'pd_order') {

            $result = $logic_payment->getPdOrderInfo($out_trade_no);
            if ($result['data']['pdr_payment_state'] == 1) {
                exit($success);
            }

        } else {
            exit();
        }
        $order_pay_info = $result['data'];

        //取得支付方式
        $result = $logic_payment->getPaymentInfo($_GET['payment_code']);
        if (!$result['state']) {
            exit($fail);
        }
        $payment_info = $result['data'];

        //创建支付接口对象
        $payment_api = new $payment_info['payment_code']($payment_info, $order_pay_info);

        //对进入的参数进行远程数据判断
        $verify = $payment_api->notify_verify();
        if (!$verify) {
            exit($fail);
        }

        //购买商品
        if ($order_type == 'real_order') {
            $result = $logic_payment->updateRealOrder($out_trade_no, $payment_info['payment_code'], $order_list, $trade_no);
        } elseif ($order_type == 'vr_order') {
            $result = $logic_payment->updateVrOrder($out_trade_no, $payment_info['payment_code'], $order_pay_info, $trade_no);
        } elseif ($order_type == 'pd_order') {
            $result = $logic_payment->updatePdOrder($out_trade_no, $trade_no, $payment_info, $order_pay_info);
        }

        exit($result['state'] ? $success : $fail);
    }



    /**
     * 通知处理(微信异步通知)
     *
     */
    public function wxpay_notifyOp()
    {
        $arr = file_get_contents("php://input");
        $logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
        $a = $logHandler->write($arr);
        var_dump($a);
        DIE;
        $date['type']=1;
        $date['time']=time();
//        if ($_POST['return_code']=='SUCCESS'){
//            if ($_POST['attach']){
//                $attach = json_decode($_POST['attach']);
//                if ($attach['type']!=1){
//                    $date['type']=2;
//                }
//            }
//            $date['msg']= json_encode($_POST,JSON_UNESCAPED_UNICODE);
//            $date['status'] = 1;
//        }else{
//            if ($_POST['attach']){
//                $attach = json_decode($_POST['attach']);
//                if ($attach['type']!=1){
//                    $date['type']=2;
//                }
//            }
//            $date['status'] = 0;
//        }
        $log_mdoel = Model('wxpay_log');
        $log_mdoel->addWxpayLog($date);
        var_dump('你好');
        var_dump(date("YmdHis"));
        die;



        switch ($_GET['payment_code']) {
            case 'alipay':
                $success = 'success';
                $fail = 'fail';
                break;
            case 'wxpay':
                $success = 'success';
                $fail = 'fail';
                break;
            case 'chinabank':
                $success = 'ok';
                $fail = 'error';
                break;
            default:
                exit();
        }

        $order_type = $_POST['extra_common_param'];
        $out_trade_no = $_POST['out_trade_no'];
        $trade_no = $_POST['trade_no'];

        //参数判断
        if (!preg_match('/^\d{18}$/', $out_trade_no)) exit($fail);

        $model_pd = Model('predeposit');
        $logic_payment = Logic('payment');

        if ($order_type == 'real_order') {

            $result = $logic_payment->getRealOrderInfo($out_trade_no);
            if (intval($result['data']['api_pay_state'])) {
                exit($success);
            }
            $order_list = $result['data']['order_list'];

        } elseif ($order_type == 'vr_order') {

            $result = $logic_payment->getVrOrderInfo($out_trade_no);
            if ($result['data']['order_state'] != ORDER_STATE_NEW) {
                exit($success);
            }

        } elseif ($order_type == 'pd_order') {

            $result = $logic_payment->getPdOrderInfo($out_trade_no);
            if ($result['data']['pdr_payment_state'] == 1) {
                exit($success);
            }

        } else {
            exit();
        }
        $order_pay_info = $result['data'];

        //取得支付方式
        $result = $logic_payment->getPaymentInfo($_GET['payment_code']);
        if (!$result['state']) {
            exit($fail);
        }
        $payment_info = $result['data'];

        //创建支付接口对象
        $payment_api = new $payment_info['payment_code']($payment_info, $order_pay_info);

        //对进入的参数进行远程数据判断
        $verify = $payment_api->notify_verify();
        if (!$verify) {
            exit($fail);
        }

        //购买商品
        if ($order_type == 'real_order') {
            $result = $logic_payment->updateRealOrder($out_trade_no, $payment_info['payment_code'], $order_list, $trade_no);
        } elseif ($order_type == 'vr_order') {
            $result = $logic_payment->updateVrOrder($out_trade_no, $payment_info['payment_code'], $order_pay_info, $trade_no);
        } elseif ($order_type == 'pd_order') {
            $result = $logic_payment->updatePdOrder($out_trade_no, $trade_no, $payment_info, $order_pay_info);
        }

        exit($result['state'] ? $success : $fail);
    }
    /**
     * 支付接口返回
     *
     */
    public function returnOp()
    {
        $order_type = $_GET['extra_common_param'];
        if ($order_type == 'real_order') {
            $act = 'member_order';
        } elseif ($order_type == 'vr_order') {
            $act = 'member_vr_order';
        } elseif ($order_type == 'pd_order') {
            $act = 'predeposit';
        } else {
            exit();
        }

        $out_trade_no = $_GET['out_trade_no'];
        $trade_no = $_GET['trade_no'];
        $url = SHOP_SITE_URL . '/index.php?act=' . $act;

        //对外部交易编号进行非空判断
        if (!preg_match('/^\d{18}$/', $out_trade_no)) {
            showMessage('参数错误', $url, '', 'html', 'error');
        }

        $logic_payment = Logic('payment');

        if ($order_type == 'real_order') {

            $result = $logic_payment->getRealOrderInfo($out_trade_no);
            if (!$result['state']) {
                showMessage($result['msg'], $url, 'html', 'error');
            }
            if ($result['data']['api_pay_state']) {
                $payment_state = 'success';
            }
            $order_list = $result['data']['order_list'];

        } elseif ($order_type == 'vr_order') {

            $result = $logic_payment->getVrOrderInfo($out_trade_no);
            if (!$result['state']) {
                showMessage($result['msg'], $url, 'html', 'error');
            }
            if ($result['data']['order_state'] != ORDER_STATE_NEW) {
                $payment_state = 'success';
            }

        } elseif ($order_type == 'pd_order') {

            $result = $logic_payment->getPdOrderInfo($out_trade_no);
            if (!$result['state']) {
                showMessage($result['msg'], $url, 'html', 'error');
            }
            if ($result['data']['pdr_payment_state'] == 1) {
                $payment_state = 'success';
            }
        }
        $order_pay_info = $result['data'];
        $api_pay_amount = $result['data']['api_pay_amount'];

        if ($payment_state != 'success') {
            //取得支付方式
            $result = $logic_payment->getPaymentInfo($_GET['payment_code']);
            if (!$result['state']) {
                showMessage($result['msg'], $url, 'html', 'error');
            }
            $payment_info = $result['data'];

            //创建支付接口对象
            $payment_api = new $payment_info['payment_code']($payment_info, $order_pay_info);

            //返回参数判断
            $verify = $payment_api->return_verify();
            if (!$verify) {
                showMessage('支付数据验证失败', $url, 'html', 'error');
            }

            //取得支付结果
            $pay_result = $payment_api->getPayResult($_GET);
            if (!$pay_result) {
                showMessage('非常抱歉，您的订单支付没有成功，请您后尝试', $url, 'html', 'error');
            }

            //更改订单支付状态
            if ($order_type == 'real_order') {
                $result = $logic_payment->updateRealOrder($out_trade_no, $payment_info['payment_code'], $order_list, $trade_no);
            } else if ($order_type == 'vr_order') {
                $result = $logic_payment->updateVrOrder($out_trade_no, $payment_info['payment_code'], $order_pay_info, $trade_no);
            } else if ($order_type == 'pd_order') {
                $result = $logic_payment->updatePdOrder($out_trade_no, $trade_no, $payment_info, $order_pay_info);
            }
            if (!$result['state']) {
                showMessage('支付状态更新失败', $url, 'html', 'error');
            }
        }

        //支付成功后跳转
        if ($order_type == 'real_order') {
            $pay_ok_url = SHOP_SITE_URL . '/index.php?act=buy&op=pay_ok&pay_sn=' . $out_trade_no . '&pay_amount=' . ncPriceFormat($api_pay_amount);
        } elseif ($order_type == 'vr_order') {
            $pay_ok_url = SHOP_SITE_URL . '/index.php?act=buy_virtual&op=pay_ok&order_sn=' . $out_trade_no . '&order_id=' . $order_pay_info['order_id'] . '&order_amount=' . ncPriceFormat($api_pay_amount);
        } elseif ($order_type == 'pd_order') {
            $pay_ok_url = SHOP_SITE_URL . '/index.php?act=predeposit';
        }
        if ($payment_info['payment_code'] == 'tenpay') {
            showMessage('', $pay_ok_url, 'tenpay');
        } else {
            redirect($pay_ok_url);
        }
    }

    function _amount_pay($pay_info, $payment_info, $url)
    {

        //查询用户余额
        $uid = $pay_info['buyer_id'];
        $model = Model('Member');
        $amount = ($model->where(['member_id' => $uid])->field('available_predeposit')->find())['available_predeposit'];

        if ($amount < $pay_info['api_pay_amount']) {
            showMessage('余额不足支付失败', $url, 'html', 'error');
        }

        $total = $amount - $pay_info['api_pay_amount'];
        if (!$model->where(['member_id' => $uid])->update(['available_predeposit' => $total])) {
            showMessage('支付失败', $url, 'html', 'error');
        }

        $logic_payment = Logic('payment');

        $result = Logic('payment')->updateRealOrder('', $payment_info['payment_code'], $pay_info['order_list'], '');

//        $model->where()
    }

    /**
     * 新的支付宝支付
     * @author: yanggang
     * @date: 2018/9/7 0007
     * @param $order_info
     * @param $payment_info
     * @throws Exception
     */
    public function _alipay($order_info, $payment_info)
    {
        $Pay = new AlipayGather();
        $result = $Pay->PCPay($order_info);
        echo $result;
    }

    /**
     * 新的支付宝异步通知回调方法
     * @author: yanggang
     * @date: 2018/9/7 0007
     * @throws Exception
     */
    public function alipay_notifyOp()
    {
        $success = 'success';
        $fail = 'fail';

        unset($_POST['act']);
        unset($_POST['op']);

        //记录日志
        $data = json_encode($_POST, JSON_UNESCAPED_UNICODE);
        $insert_id = db::insert('alipay_log',['msg'=>$data]);

        $_POST['fund_bill_list'] = htmlspecialchars_decode($_POST['fund_bill_list']);

        $flag = (new AlipayGather())->check($_POST);

        if ($flag){
            db::update('alipay_log',['is_check'=>1],'id='.$insert_id);
        }

        //验签成功，处理订单
        $common_params = [];
        parse_str(urldecode($_POST['passback_params']),$common_params);
        $order_type = $common_params['order_type'];
        $out_trade_no = $_POST['out_trade_no'];
        $trade_no = $_POST['trade_no'];

        //参数判断
        if (!preg_match('/^\d{18}$/', $out_trade_no)) exit($fail);

        $model_pd = Model('predeposit');
        $logic_payment = Logic('payment');

        if ($order_type == 'real_order') {

            $result = $logic_payment->getRealOrderInfo($out_trade_no);
            if (intval($result['data']['api_pay_state'])) {
                exit($success);
            }
            $order_list = $result['data']['order_list'];

        } elseif ($order_type == 'vr_order') {

            $result = $logic_payment->getVrOrderInfo($out_trade_no);
            if ($result['data']['order_state'] != ORDER_STATE_NEW) {
                exit($success);
            }

        } elseif ($order_type == 'pd_order') {

            $result = $logic_payment->getPdOrderInfo($out_trade_no);
            if ($result['data']['pdr_payment_state'] == 1) {
                exit($success);
            }

        } else {
            exit();
        }
        $order_pay_info = $result['data'];

        //取得支付方式
//        $result = $logic_payment->getPaymentInfo($_GET['payment_code']);
//        if (!$result['state']) {
//            exit($fail);
//        }
//        $payment_info = $result['data'];
//
//        //创建支付接口对象
//        $payment_api = new $payment_info['payment_code']($payment_info, $order_pay_info);
//
//        //对进入的参数进行远程数据判断
//        $verify = $payment_api->notify_verify();
//        if (!$verify) {
//            exit($fail);
//        }
        //验签失败，退出
        if (!$flag){
            exit($fail);
        }

        //购买商品
        if ($order_type == 'real_order') {
            $result = $logic_payment->updateRealOrder($out_trade_no, 'alipay', $order_list, $trade_no);
        } elseif ($order_type == 'vr_order') {
            $result = $logic_payment->updateVrOrder($out_trade_no, 'alipay', $order_pay_info, $trade_no);
        } elseif ($order_type == 'pd_order') {
            $result = $logic_payment->updatePdOrder($out_trade_no, $trade_no, ['payment_code'=>'alipay','payment_name'=>'支付宝'], $order_pay_info);
        }

        exit($result['state'] ? $success : $fail);


    }

    /**
     * 新的支付宝同步通知回调方法
     * @author: yanggang
     * @date: 2018/9/7 0007
     */
    public function alipay_returnOp()
    {
        $data = $_GET;
        $pay_ok_url = SHOP_SITE_URL . '/index.php?act=member_order';
        redirect($pay_ok_url);

//        //支付成功后跳转
//        if ($order_type == 'real_order') {
//            $pay_ok_url = SHOP_SITE_URL . '/index.php?act=buy&op=pay_ok&pay_sn=' . $out_trade_no . '&pay_amount=' . ncPriceFormat($api_pay_amount);
//        } elseif ($order_type == 'vr_order') {
//            $pay_ok_url = SHOP_SITE_URL . '/index.php?act=buy_virtual&op=pay_ok&order_sn=' . $out_trade_no . '&order_id=' . $order_pay_info['order_id'] . '&order_amount=' . ncPriceFormat($api_pay_amount);
//        } elseif ($order_type == 'pd_order') {
//            $pay_ok_url = SHOP_SITE_URL . '/index.php?act=predeposit';
//        }
//        if ($payment_info['payment_code'] == 'tenpay') {
//            showMessage('', $pay_ok_url, 'tenpay');
//        } else {
//            redirect($pay_ok_url);
//        }
    }

    public function alipay_getOp()
    {

        $a = '[{&quot;amount&quot;:&quot;0.01&quot;,&quot;fundChannel&quot;:&quot;ALIPAYACCOUNT&quot;}]';
//        db::update('alipay_log',['is_check'=>1],'id=14');


        $row = db::getAll('select * from shopnc_alipay_log where id = 2');
        $data = json_decode($row[0]['msg'], true);
        $data['fund_bill_list'] = htmlspecialchars_decode($data['fund_bill_list']);
        $params = urldecode($data['passback_params']);
        parse_str($params,$a);

        $str ='';
        foreach ($data as $k=>$v){
            $str .= '&'.$k.'='.$v;
        }

        $str = ltrim($str,'&');
        file_put_contents('alipay.txt',$str);
//        $str = '';
//        foreach ($data as $k=>$v){
//            if ($k =='fund_bill_list'){
//                $data[$k] = htmlspecialchars_decode($v);
//            }else{
//                $data[$k] = urldecode($v);
//            }
//
//            $str .= '&'.$k.'='.$v;
//        }
//
//        print_r($str);
//        var_dump($data);

        $flag = (new AlipayGather())->check($data);

exit();


    }


}